package org.software.dao;
import org.software.entity.Group;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class GroupDataProvider {
    private static AtomicInteger groupIdGenerator = new AtomicInteger(0);
    private static List<Group> groups = new CopyOnWriteArrayList<>();

    public static boolean groupAdd(String groupName, String className) {
        for (Group group : groups) {
            if (group.getGroupName().equals(groupName)) {
                return false;//已存在
            }
        }
        Group newGroup = new Group(groupIdGenerator.incrementAndGet(), groupName, className,0);
        groups.add(newGroup);
        return true;//添加成功
    }
    public static boolean groupDelete(String groupName) {
        for (Group group : groups) {
            if (group.getGroupName().equals(groupName)) {
                ClassDataProvider.decrementGroupCountForClass(group.getClassName());
                groups.remove(group);
                return true;
            }
        }
        return false;
    }
    public static boolean groupUpdate(String oldGroupName, String newGroupName) {
        for (Group group : groups) {
            if (group.getGroupName().equals(oldGroupName)) {
                group.setGroupName(newGroupName);
                return true;
            }
        }
        return false;
    }

    public static List<Group> groupQuery() {
        return new ArrayList<>(groups);
    }
    public static void incrementStudentCountForGroup(String groupName) {
        for (Group group : groups) {
            if (group.getGroupName().equals(groupName)) {
                group.setStudentCount(group.getStudentCount()+1);
                break;
            }
        }
    }
    public static Group getRandomGroup(){
        if(groups.isEmpty()){
            return null;
        }
        int index = (int)(Math.random()*groups.size());
        return groups.get(index);
    }
    public static void decrementStudentCountForGroup(String groupName) {
        for (Group group : groups) {
            if (group.getGroupName().equals(groupName)) {
                int currentCount = group.getStudentCount();
                if (currentCount > 0) {
                    group.setStudentCount(currentCount-1);
                }
                break;
            }
        }
    }
}